import __config from '@/config/env';

const scope = 'server';

export const request = (url, method, data = null, showLoading = false) => {
    let _url = __config.basePath + url;
    let userInfo = uni.getStorageSync('userLoginInfo') ? JSON.parse(uni.getStorageSync('userLoginInfo')) : null;
    let fixedToken;
    if (url.includes('/auth/validate/code/text')) {
        fixedToken = 'Basic fHuoFMzT2Dne3nWPTKcu+Q==';
    }

    if (url.includes('/auth/oauth/token') || url.includes('/auth/phone/token/sms') || url.includes(
            '/upms/user/password/reset') || url.includes('/agentmerchantadmin/area/sub_area')) {
        fixedToken = 'Basic YWRtaW46YWRtaW4=';
    }


    return new Promise(async (resolve, reject) => {
        if (showLoading) {
            uni.showLoading();
        }

        if (userInfo) {
            // const curDateTime = new Date().getTime();
            const curDateTime = new Date().getTime() + 120 * 1000;
            if (curDateTime > userInfo.expires_in) {
                await refreshToken().then(response => {
                    let result = response
                    result.expires_in = new Date().getTime() + result.expires_in * 1000;
                    uni.setStorageSync('userLoginInfo', JSON.stringify(result));
                    userInfo = result
                }).catch(response => {
                    //失败 重新登录
                    uni.hideLoading();
                    reject();
                    return;
                });

            }
        }
        let token = fixedToken ? fixedToken : userInfo ? 'Bearer ' + userInfo.access_token : ''

        uni.request({
            url: _url,
            method: method,
            data: data,
            withCredentials: true,
            header: {
                'client-type': 'APP', //客户端类型APP
                'Identity-Type': uni.getStorageSync('userRole'),
                'tenant-id': __config.tenantId,
                Authorization: token
            },
            success(res) {
                if (showLoading) {
                    uni.hideLoading();
                }
                if (res.statusCode == 200) {
                    if (res.data.code && res.data.code != 0) {
                        if (res.data.code == 60001 || res.data.code == 60002) {
                            // 心跳接口不处理
                            if (_url.indexOf('useronline/heartbeat') != -1) {
                                // 不做处理
                            } else if (!getApp().globalData.logining) {
                                getApp().globalData.logining = true; //防止同时多个接口触发登录
                                if (util.isMiniPg() || (getApp().globalData.appId && util
                                        .isWeiXinBrowser())) {
                                    //小程序或公众号H5，删除third_session重新登录
                                    uni.removeStorageSync('third_session');
                                    getApp()
                                        .doLogin()
                                        .then((res) => {
                                            var pages = getCurrentPages(); // 获取页面栈
                                            var currPage = pages[pages.length - 1]; // 当前页面
                                            currPage.onLoad(currPage.options);
                                            currPage.onShow();
                                        });
                                } else {
                                    util.backLoginPage();
                                }
                                setTimeout(function() {
                                    getApp().globalData.logining = false;
                                }, 2000);
                            }
                            reject('session过期重新登录');
                        } else if (res.data.code == 60003) {
                            if (!getApp().globalData.logining2) {
                                getApp().globalData.logining2 = true; //防止同时多个接口触发登录
                                util.backLoginPage();
                                setTimeout(function() {
                                    getApp().globalData.logining2 = false;
                                }, 2000);
                            }
                            reject('请先登录商城');
                        } else {
                            if (res.data.errCode || res.data.errCode == 0) {
                                //兼容im返回
                                resolve(res.data);
                            } else {
                                let errMsg = res.data.msg || res.errMsg;
                                uni.showToast({
                                    icon: 'none',
                                    title: errMsg,
                                    duration: 3000
                                });
                                reject(res.data.msg);
                            }
                        }
                    }
                    resolve(res.data);
                } else if (res.statusCode == 404) {
                    uni.showToast({
                        icon: 'none',
                        title: '接口请求出错，请检查手机网络',
                        duration: 3000
                    });
                    reject();
                } else if (res.statusCode == 500) {
                    if (res.data.msg) {
                        if (res.data.msg != 'UnknownHostException: http') {
                            uni.showModal({
                                title: '提示',
                                content: res.data.msg,
                                confirmText: '确定',
                                showCancel: false,
                                success: (res) => {}
                            });
                            reject();
                        }
                    }
                } else if (res.statusCode == 502) {
                    uni.showToast({
                        icon: 'none',
                        title: '服务器维护中，请稍后再来',
                        duration: 3000
                    });
                    reject();
                } else if (res.statusCode == 503) {
                    uni.showToast({
                        title: '503错误，服务未启动',
                        icon: 'none',
                        duration: 3000
                    });
                    reject();
                } else if (res.statusCode == 401 && res.data.data == 'invalid_token') {
                    uni.showToast({
                        title: '登录过期，请重新登录',
                        icon: 'none',
                        duration: 3000
                    });
                    uni.clearStorageSync()
                    setTimeout(() => {
                        uni.reLaunch({
                            url: '/pages_user/Login_Register/Login_Register'
                        })
                    }, 2000)
                    reject();
                } else {
                    uni.showModal({
                        title: '提示',
                        content: '错误：' + res.data.msg,
                        success(res) {}
                    });
                    // reject(res);
                    reject();
                }
            },
            fail(error) {
                //3提示无网络
                if (showLoading) {
                    uni.hideLoading();
                }
                if (error.errMsg && error.errMsg.indexOf('statusCode:-1') != -1) {
                    console.log('无网络');
                } else if (getApp().globalData.hasNetwork) {
                    // 忽略该错误 带有interrupted的 一般都是小程序切后台中断导致的 https://zhuanlan.zhihu.com/p/453875594
                    let ignoreErrMsg = 'network api interrupted in suspend state';
                    console.log(_url, 999);
                    if (error.errMsg) {
                        if (error.errMsg.indexOf('network api interrupted in suspend state') ==
                            -
                            1) {
                            uni.showToast({
                                icon: 'none',
                                title: '接口请求出错：' + error.errMsg,
                                duration: 3000
                            });
                        }
                    } else {
                        uni.showToast({
                            icon: 'none',
                            title: '接口请求出错：' + error,
                            duration: 3000
                        });
                    }
                } else {
                    uni.showToast({
                        icon: 'none',
                        title: '无法连接到网络'
                    });
                }
                reject(error);
            }
        });
    });
}



const refreshToken = () => {
    const userInfo = uni.getStorageSync('userLoginInfo') ? JSON.parse(uni.getStorageSync('userLoginInfo')) : null;
    // token过期，刷新token
    const refresh_token = userInfo.refresh_token;
    const grant_type = 'refresh_token';
    const query = '?refresh_token=' + refresh_token +
        '&grant_type=' + grant_type +
        '&scope=' + scope;
    return new Promise((resolve, reject) => {
        requestNotValidate('/auth/oauth/token' + query, 'POST', null, false).then(response => {
            // 登录成功 保存登录数据、本次登录的token 
            resolve(response);
        }).catch(response => {
            //失败 重新登录 

            uni.clearStorageSync()

            uni.showToast({
                icon: 'none',
                position: 'bottom',
                title: '身份验证信息已失效,请重新登录'
            });
            uni.reLaunch({
                url: '/pages_user/Login_Register/Login_Register'
            })
            reject();
        });
    });
}


// 不需要验证的接口，如登录时的接口
const requestNotValidate = (url, method, data, showLoading) => {
    let _url = __config.basePath + url;
    return new Promise((resolve, reject) => {
        if (showLoading) {
            uni.showLoading({
                title: '加载中'
            });
        }
        uni.request({
            url: _url,
            method: method,
            data: data,
            withCredentials: true,
            header: {
                isToken: false,
                'Authorization': 'Basic YWRtaW46YWRtaW4=',
                'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8'
            },
            success(res) {
                uni.hideLoading();
                if (res.statusCode == 200) {
                    resolve(res.data);
                } else if (res.statusCode == 404) {
                    uni.showModal({
                        title: '提示',
                        content: '接口请求出错，请检查手机网络',
                        success(res) {}
                    });
                    reject();
                } else if (res.statusCode == 401 || res.statusCode == 426) {
                    uni.showToast({
                        title: res.data.msg,
                        icon: 'none',
                    });
                    reject(res.data);
                } else {
                    uni.showModal({
                        title: '提示',
                        content: res.data.msg,
                        success(res) {}
                    });
                    reject();
                }
            },
            fail(error) {
                uni.hideLoading();
                uni.showModal({
                    title: '提示',
                    content: '接口请求出错：' + error.errMsg,
                    success(res) {}
                });
                reject(error);
            },
            complete(res) {
                uni.hideLoading();
            }
        });
    });
};





/**
 * 上传文件接口
 * @param {Object} filePath 本地文件路径
 * @param {Object} dir 上传保存的文件目录, 如头像保存的目录: headimg/
 * @param {Object} fileType 文件类型说明(没有强制要求) image/video/file/...
 */

import uploadAliyun from '@/components/aliyunOss/upload/uploadAliyun.js';


export function uploadFile(filePath, dir = 'agent', fileType = 'image') {
    // 上传文件
    // let _url = '/upms/file/upload';
    // _url = __config.basePath + _url;
    // // const userInfo = JSON.parse(uni.getStorageSync('userLoginInfo'));
    // let that = this;
    uni.showLoading({
        title: '上传中'
    });

    return new Promise((resolve, reject) => {
        // uni.uploadFile({
        //     header: {
        //         'client-type': 'APP', //客户端类型APP
        //         'tenant-id': __config.tenantId,
        //         // Authorization: userInfo.token_type + ' ' + userInfo.access_token
        //     },
        //     url: _url,
        //     filePath: filePath,
        //     name: 'file',
        //     formData: {
        //         fileType: fileType,
        //         dir: dir
        //     },
        //     success: (uploadFileRes) => {
        //         uni.hideLoading();
        //         if (uploadFileRes.statusCode == '200') {
        //             let link = JSON.parse(uploadFileRes.data).link;
        //             resolve(link);
        //         } else {
        //             uni.showModal({
        //                 title: '提示',
        //                 content: '上传失败:' + uploadFileRes.data,
        //                 success(res) {}
        //             });
        //             reject();
        //         }
        //     },
        //     fail: (err) => {
        //         uni.hideLoading();
        //         console.log(err);
        //         reject();
        //     }
        // });

        // 上传前,要确保临时路径是正确的(开始上传到OSS)
        // 对于此api参数，详见uploadAliyun.js文件
        uploadAliyun({
            filePath,
            dir,
            name: `${Date.now()}_${Math.floor(Math.random() * 10000)}.${filePath.split('.').slice(-1)[0]}`,
            success: (res) => {
                console.log(res)
                uni.hideLoading();
                if (res.code == 200) {
                    let link = res.oss_file;
                    resolve(link);
                } else {
                    uni.showModal({
                        title: '提示',
                        content: '上传失败:' + res.msg,
                        success(res) {}
                    });
                    reject();
                }
            },
            fail: (err) => {
                uni.showModal({
                    title: '提示',
                    content: err.msg || err.message || '上传失败',
                    success(res) {}
                });
                reject();
            }
        })


    });
}